package com.sfddata.musicpillow.gateway.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class JwtUtil {

    public static void main(String[] args) throws Exception {
        String jwt = JwtUtil.createJWT(UUID.randomUUID().toString(), "jyo960711", null);
        Claims claims = parseJWT(jwt);
        System.out.println(claims);
    }

    // 有效期30天
    private static final Long JWT_TTL = 1000L * 60 * 60 * 24 * 30;
    // 明文密钥
    private static final String JWT_KEY ="sfdJWTKey";

    /**
     * 解析认证token
     * token不合法的时候会发生异常
     * @param token
     * @return
     */
    public static Claims parseJWT(String token) throws Exception{
        SecretKey secretKey = generalKey();
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
    }

    /**
     * 生成密钥
     * @return
     */
    public static SecretKey generalKey(){

        byte[] encode = Base64.getEncoder().encode(JwtUtil.JWT_KEY.getBytes());
        // 最后一个参数是自定义密钥
        SecretKey secretKey = new SecretKeySpec(encode, 0, encode.length, "AES");
        return secretKey;
    }

    /**
     *
     * @param id 编号
     * @param subject 主题
     * @param TTLMills 有效期
     * @return
     */
    public static String createJWT(String id, String subject, Long TTLMills){

        if (TTLMills == null){
            TTLMills = JWT_TTL;
        }
        Date expDate = new Date(System.currentTimeMillis() + TTLMills);
        // 获得密文
        SecretKey secretKey = generalKey();
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(id)
                .setSubject(subject)
                .setIssuer("admin")
                .setIssuedAt(new Date())
                .setExpiration(expDate)
                .signWith(SignatureAlgorithm.HS256, secretKey);

        return jwtBuilder.compact();
    }
}
